package com.csii.ams.controller;


import com.csii.adhoc.annotation.OperationLog;
import com.csii.adhoc.id.UidGenerator;
import com.csii.adhoc.info.user.UserPo;
import com.csii.adhoc.info.user.service.UserService;
import com.csii.adhoc.util.DateUtils;
import com.csii.ams.AmsLog;
import com.csii.ams.service.AmsLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: panchuanjiang
 * @Date: 2021/01/12/9:30
 * @Description: 日志切面
 */
//@Aspect
//@Component("amsLog")
public class AsyncLogAspect{

    protected final Logger logger = LoggerFactory.getLogger(AsyncLogAspect.class);

    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
            5, 60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(50), new ThreadPoolExecutor.DiscardPolicy());

    @Resource
    private AmsLogService amsLogService;
    @Resource
    private UserService userService;
    @Resource
    private UidGenerator uidGenerator;
    @Autowired
    private HttpServletRequest request;

    @AfterReturning("@annotation(operationLog)")
    public void afterReturning(OperationLog operationLog) throws Throwable {
        HttpSession session = request.getSession();
        String userId = String.valueOf(SecurityUtils.getSubject().getPrincipal());
        UserPo user = userService.selectUserByUserName(userId);
        if (user == null){
            return;
        }
        String logName = operationLog.value();
        //String optime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        AmsLog amsLog = new AmsLog();
        amsLog.setOpSeqno(uidGenerator.getUID()+"");
        amsLog.setOpTyp("00");
        amsLog.setInstNo("00");
        amsLog.setArchCd("11111");//todo 档案名称
        amsLog.setCustNo(userId);
        amsLog.setCustNm(user.getName());
        amsLog.setCertId(user.getIdCard());
        amsLog.setOpPurp(logName);
        amsLog.setOpDt(DateUtils.getDateString("yyyyMMdd"));
        amsLog.setOpTm(DateUtils.getDateString("HHmmss"));
        amsLog.setOpTl(user.getName());
        executor.execute(() -> amsLogService.insertAmsLog(amsLog));
    }
}
